<?php
/**
 * @version 	$Id: fUser.class.php 84 2010-03-18 00:06:10Z mylifeisskidrow@gmail.com $
 * @author 		$Author: mylifeisskidrow $
 * @copyright 	Copyright (c) 2010 Luu Trong Hieu. All right reserved.
 * @license 	GNU/GPL see license.php
 */

defined('IN_FLYWHEEL') or die('Restriced Access!');

/**
 * Flywheel Database User
 * 
 * @package 	system
 * @subpackage 	user
 *
 */

class fUser implements fSecurityUserInterface {
	protected $_id;
	protected $_authenticated = false;
	protected $_attributes = array();
	protected $_lastRequest;
	protected $_groups = array();
	protected $_permissions = array();
	protected $_culture;
	
	/**
	 * Construct
	 */
	public function __construct() {		
		register_shutdown_function(array($this, 'shutdown'));
		if (fFactory::getSession()->has('user')) {
			$user = fFactory::getSession()->get('user');
			foreach (get_object_vars($user) as $property=> $value) {
				$this->$property = $value;							
			}					
		}
	}
	
	/**
	 * Set Culture for fUser
	 *
	 * @param mixed|string|fCultureInfo $locate
	 */
	public function setCulture($locate = 'en') {
		if ($locate == null) {
			$locate = fCultureInfo::getInstance(fConfig::get('default/culture_info', 'routing'));	
		}
		
		if ($locate instanceof fCultureInfo ) {
			$this->_culture = $locate;
		}
		else {
			$this->_culture = fCultureInfo::getInstance($locate);
		}
		
	}
	
	/**
	 * Get Culture Info of User
	 *
	 * @return fCultureInfo
	 */
	public function getCulture() {
		if ($this->_culture == null) {
			$this->_culture = fCultureInfo::getInstance(fConfig::get('default/culture_info', 'routing'));		
		}
		
		return $this->_culture;
	}
	
	/**
	 * Check authenticated of User
	 *
	 * @return boolean
	 */
	public function isAuthenticated() {
		return $this->_authenticated;
	}
	
	/**
	 * Set Authenticated for User
	 *
	 * @param boolean $authenticated
	 */
	public function setAuthenticated($authenticated) {
		$this->_authenticated = (boolean) $authenticated;
	}
	
	public function hasPermission() {		
	}
	
	public function addPermission() {
		if (func_num_args() === 0) return;
		$permissions = func_get_args();
		if (is_array($permissions)) {
			for ($i = 0, $size = sizeof($permissions); $i < $size; ++$i) {
				$this->_permissions[$permissions[$i]] = true;						 
			}
		}
	}
	
	public function hasPermissions($permissions) {
		$permission = explode(' ', $permissions);
		for($i = 0, $size = sizeof($permission); $i < $size; $i+=2) {
			$permission[$i] = isset($this->_permissions[$permission[$i]])? 
								$this->_permissions[$permission[$i]] : false;			
		}

		$str = 'return ' . implode(' ', $permission) .';';
		return eval($str);
	}
	
	public function removePermission($permission) {
		if (isset($this->_permissions[$permission])) {
			unset($this->_permissions[$permission]);		
		}
	}
	
	public function clearPermission() {
		$this->_permissions = array();	
	}
	
	/**
	 * Login
	 *
	 * @param string $username
	 * @param string $password
	 * @return boolean
	 */
	public function login($username, $password) {		
		$q = Doctrine_Query::create()
				->select('u.*')
				->from('User as u')
				->where('u.username = ? AND u.status = 1', $username)
				->limit(1);
		$user = $q->fetchOne();
		if ($user === false) {// User not found
			
		}
		else if ($user->status != 1) { // User not active
			
		}
		else {
			$encryptPassword = explode(':', $user->password);
			if ($encryptPassword[0] == md5($password.$encryptPassword[1])) {
				$userToArray = $user->toArray(true);
				unset($userToArray['id']);
				unset($userToArray['password']);
				$this->_attributes = $userToArray;
				$this->_id = $user->id;
				$this->_lastRequest = time();
				$this->_authenticated = true;				
				
				//Update last login
				$user->last_login = time();
				$user->save();
				
				return true;
			}
		}
		return false;
	}
	
	public function logout() {
		$this->_id = null;
		$this->_attributes = array();
		$this->clearPermission();
		$this->_authenticated = false;
		$this->_culture = null;
		fFactory::getSession()->set('user', $this);
	}
	
	public function getId() {
		return $this->_id;
	}
	
	public function getLastRequest() {
		return $this->_lastRequest;
	}
	
	public function getAttribute($name, $default = null) {
		if (isset($this->_attributes[$name])) {
			return $this->_attributes[$name];
		}
		
		return $default;
	}
	
	/**
	 * Create Salt
	 * create salt string for password
	 * 
	 * @return md5 string
	 *
	 */
	public static function createSalt($lenght = '15') {
		$characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
		$characterLenght = strlen($characterList);
		$salt = '';
		for($i = 0; $i < $lenght; ++$i) {
			$salt .= $characterList[mt_rand($i, $characterLenght)];			
		}
		
		$salt .= time();
		return md5($salt);				
	}
	
	/**
	 * Shutdown
	 *
	 */
	public function shutdown() {
		$session = fFactory::getSession();
		$session->set('user', $this);
	}
}